#!/usr/bin/python
# -*- coding: UTF-8 -*-
import database
import sys
import json
import collections
import numpy as np
import pandas as pd

reload(sys)
sys.setdefaultencoding('utf8')

class MedicineVector:
    def __init__(self):
        self.all_med_list = self.__getAllMedList()

    def __getZgydDict(self):
        try:
            fp = open('./med_dict/med_zgyd.json', 'r')
        except FileOperateError, e:
            print 'open zgyd dict error'

        zgyd_dict = fp.read()
        fp.close()

        try:
            zgyd_dict = json.loads(zgyd_dict)
        except StandardError, e:
            print 'json decode error'

        return zgyd_dict

    def __getZydcdDict(self):
        try:
            fp = open('./med_dict/med_zydcd.json', 'r')
        except FileOperateError, e:
            print 'open zydcd dict error'

        zydcd_dict = fp.read()
        fp.close()

        try:
            zydcd_dict = json.loads(zydcd_dict)
        except StandardError, e:
            print 'json decode error'

        return zydcd_dict

    def __getZhbcDict(self):
        try:
            fp = open('./med_dict/med_zhbc.json', 'r')
        except FileOperateError, e:
            print 'open zhbc dict error'

        zhbc_dict = fp.read()
        fp.close()

        try:
            zhbc_dict = json.loads(zhbc_dict)
        except StandardError, e:
            print 'json decode error'

        return zhbc_dict

    def __getAllMedList(self):
        zgyd_list   = self.__getZgydDict()
        zydcd_list  = self.__getZydcdDict()
        zhbc_list   = self.__getZhbcDict()

        all_med_list = [
            zgyd_list,
            zydcd_list,
            zhbc_list
        ]

        return all_med_list

    def __getMedicineNameDict(self):
        name_dict = collections.OrderedDict()
        for one_list in self.all_med_list:
            for med_item in one_list:
                if not name_dict.has_key(med_item['title']):
                    name_dict[med_item['title']] = []
                    name_dict[med_item['title']].append(med_item['alias'])
                else:
                    name_dict[med_item['title']].append(med_item['alias'])

        return name_dict

    def getStandardName(self, alias_name):
        name_dict = self.__getMedicineNameDict()

        for (std_name, alias_list) in name_dict.items():
            if std_name == alias_name:
                return std_name

        for (std_name, alias_list) in name_dict.items():
            for alias_item in alias_list:
                if alias_name in alias_item:
                    return std_name

        return ""

    def __getMedicinePropVectorDict(self):
        prop_dict = collections.OrderedDict()
        for one_list in self.all_med_list:
            for med_item in one_list:
                if med_item['prop'] != "" and not prop_dict.has_key(med_item['title']):
                    prop_dict[med_item['title']] = med_item['prop']

        return prop_dict

    def __buildStandardPropVector(self, str_prop):
        std_taste_vector = collections.OrderedDict()
        std_taste_vector["微苦"] = 1
        std_taste_vector["微甘"] = 1
        std_taste_vector["微咸"] = 1
        std_taste_vector["微辛"] = 1
        std_taste_vector["微酸"] = 1
        std_taste_vector["淡"] = 0
        std_taste_vector["苦"] = 2
        std_taste_vector["甘"] = 2
        std_taste_vector["咸"] = 2
        std_taste_vector["辛"] = 2
        std_taste_vector["酸"] = 2

        std_taste_template = collections.OrderedDict()
        std_taste_template["淡"] = 0
        std_taste_template["苦"] = 0
        std_taste_template["甘"] = 0
        std_taste_template["咸"] = 0
        std_taste_template["辛"] = 0
        std_taste_template["酸"] = 0

        for (taste_prop, taste_value) in std_taste_vector.items():
            if taste_prop in str_prop:
                taste_prop = str(taste_prop).replace("微", "")
                std_taste_template[taste_prop] = taste_value

        result_taste_vector = std_taste_template.values()

        std_smell_vector = collections.OrderedDict()
        std_smell_vector["大热"] = 4
        std_smell_vector["微温"] = 1
        std_smell_vector["微寒"] = -2
        std_smell_vector["大寒"] = -4
        std_smell_vector["热"] = 3
        std_smell_vector["温"] = 2
        std_smell_vector["平"] = 0
        std_smell_vector["凉"] = -1
        std_smell_vector["寒"] = -3

        std_smell_template = collections.OrderedDict()
        std_smell_template["主性"] = 0
        std_smell_template["性一"] = 0
        std_smell_template["性二"] = 0
        std_smell_template["性三"] = 0
        std_smell_template["性四"] = 0
        std_smell_template["性五"] = 0

        for (smell_prop, smell_value) in std_smell_vector.items():
            if smell_prop in str_prop:
                tmp_value = std_smell_vector[smell_prop]
                std_smell_template["主性"] = tmp_value
                break

        result_smell_vector = std_smell_template.values()

        return [result_smell_vector, result_taste_vector]

    def __getMedicinePropVector(self, med_name):
        prop_dict = self.__getMedicinePropVectorDict()

        if prop_dict.has_key(med_name):
            med_prop    = prop_dict[med_name]
            prop_vector = self.__buildStandardPropVector(med_prop)

            return prop_vector
        else:
            raise ValueError('medicine missed, no such a medicine : ' + med_name)

    def getStanardMedicine(self, med_name):
        std_med_name = self.getStandardName(med_name)

        try:
            med_vector = self.__getMedicinePropVector(std_med_name)
        except ValueError, e:
            med_vector = [[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]]

            # 错误写入文件
            fp = open('./data/err_meds.txt', 'w+')
            fp.write(med_name + '\n')
            fp.close()

            raise ValueError('medicine missed, no such a medicine : ' + med_name)

        return med_vector
